﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using HiStaff.Util;
using HiStaff.Util.Enum;
using HiStaff.Base;
using HiStaff.Control;
using HiStaff.iSystem;
using HiStaff.Domain.CO;
using Janus.Windows.UI.CommandBars;
using System.Collections;
using Janus.Windows.GridEX;
using System.Globalization;
using HiStaff.Domain.PA;
using HiStaff.Domain.Sys;
using HiStaff.Domain.LST;
using HiStaff.Domain.HU;

namespace HiStaff.iTime
{
    public partial class BaseRegisterSummary : FormBase
    {
        #region Properties

        public WorkSignGroup MngSignGroup { get; set; }

        #endregion

        #region Private Variables

        private BaseRegister _frmRgt;
        private List<LST_SALPERIOD> _lstOrgPeriod;
        private List<CO_SIGN_LST> _lstSign;
        private CO_SUM_SEARCH _objCal;
        private string _usingSignCollection = string.Empty;
        //private bool _AsynComplete = false;

        private const string APPROVESIGN_SUBFIX = "_AP";
        private const string TCMD_YEAR = "YEAR";
        private const string DDCMD_TIMEPERIOD = "TIMEPERIOD";
        private const string DDCMD_DISPLAYMODE = "DISPLAYMODE";

        private const string CTXCMD_MOVE = "MOVE";

        private const string GCOL_SELECTOR = "SELECTOR";
        private const string GCOL_EMPLOYEEID = "EMPLOYEEID";
        private const string GCOL_EMPLOYEECODE = "CODE";
        private const string GCOL_EMPLOYEENAME = "FULLNAME";
        private const string GCOL_ORGNAME = "ORGNAME";
        private const string GCOL_WORKINGDAY = "WORKINGDAY";
        private const string GCOL_SUNDAY = "SUNDAY";
        private const string GCOL_WCODE = "WCODE";
        private const string GCOL_WVALUE = "WVALUE";
        private const string GCOL_STATUSNAME = "STATUS_NAME";
        private const string GCOL_ID = "ID";
        private const string GCOL_NODATA = "NODATA";

        //private const string COL_SUNDAY = "SUNDAY";
        #endregion

        #region Constructor & Private Functions and Events

        public BaseRegisterSummary()
        {
            InitializeComponent();
        }

        protected override bool FormLoad()
        {
            try
            {
                VisibleProgressBar = true;
                VisibleStatusTextBar = true;
                SetStatusText(string.Empty, MessageIcon.Null);

                base.CreateDropdownInCommandBar(DDCMD_DISPLAYMODE, "Hiển thị", 150, 5);

                base.CreateTxtInCommandBar(TCMD_YEAR, "Năm", 40, DateTime.Now.Year.ToString());

                base.CreateDropdownInCommandBar(DDCMD_TIMEPERIOD, "Kỳ công", 80, 12);

                if (MngSignGroup != 0)
                    base.CreateCommandBar(CommandBarManager.ActionCommand.Calculate,
                                          CommandBarManager.ActionCommand.Separator,
                                          CommandBarManager.ActionCommand.New,
                                          CommandBarManager.ActionCommand.Delete,
                                          CommandBarManager.ActionCommand.Separator,
                                          CommandBarManager.ActionCommand.Exit);
                else
                    base.CreateCommandBar(CommandBarManager.ActionCommand.Calculate,
                                          CommandBarManager.ActionCommand.Separator,
                                          CommandBarManager.ActionCommand.Lock,
                                          CommandBarManager.ActionCommand.UnLock,
                                          CommandBarManager.ActionCommand.Separator,
                                          CommandBarManager.ActionCommand.Exit);

                if (LoadDisplayMode())
                {
                    LoadTimePeriodByOrg(DateTime.Now.Year);
                    LoadData(false, true);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + ex.StackTrace);
                HiStaff.Util.Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
            return true;
        }
        private void BaseRegisterSummary_Load(object sender, EventArgs e)
        {

        }

        private void BaseRegisterSummary_KeyDown(object sender, KeyEventArgs e)
        {
            SignSelectionDisplay frmSdpl;
            if (e.Control && e.Alt && e.KeyCode == Keys.V)
            {
                frmSdpl = new SignSelectionDisplay();
                frmSdpl.FormName = this.GetType().Name;
                frmSdpl.ShowDialog();
                if (frmSdpl.SelectionResult == DialogResult.OK)
                {
                    InitGrid();
                    if (txtSearchEmp.Text.Trim() == string.Empty)
                        LoadData(false, false);
                    else LoadData(true, false);
                }
            }
        }

        private void ucOrgTreeview_AfterSelect(object sender, TreeViewEventArgs e)
        {
            try
            {
                if (!IsLoaded || IsProcessing)
                {
                    return;
                }
                else
                {
                    IsProcessing = true;
                    this.Cursor = Cursors.WaitCursor;
                }

                TextBox txtYear = base.GetCommandByKey(TCMD_YEAR).GetTextBox();
                decimal year;
                bool isConvert = decimal.TryParse(txtYear.Text, out year);
                if (e.Node != null && txtYear.Text.Trim().Length >= 4 && isConvert)
                {
                    //LoadTimePeriodByOrg(Convert.ToDecimal(node.Name), year);
                    LoadData(false, true);
                }

                IsProcessing = false;
                this.Cursor = Cursors.Default;
                this.Enabled = true;
            }
            catch (Exception ex)
            {
                IsProcessing = false;
                this.Cursor = Cursors.Default;

                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                HiStaff.Util.Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
        }

        private void txtSearchEmp_KeyPress(object sender, KeyPressEventArgs e)
        {
            try
            {
                if (e.KeyChar == (char)Keys.Return)
                {
                    if (txtSearchEmp.Text.Trim() != string.Empty)
                    {
                        LoadData(true, false);
                    }
                    else
                    {
                        LoadData(false, false);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
                HiStaff.Util.Log.Instance.WriteExceptionLog(ex, this.Name + "[" + this.Text + "]");
            }
        }

        private bool LoadDisplayMode()
        {
            try
            {
                var lstSource = ConvertHelper.DataTableToList<SY_DEFAULT_LIST>(HiStaff.iSystem.Data.DATALIST.Tables["COVIEW"]);
                base.SetDataSourceToDropdownCommand(DDCMD_DISPLAYMODE, lstSource, "NAME", "ID", true);
                if (lstSource.Count > 0)
                {
                    base.GetCommandByKey(DDCMD_DISPLAYMODE).GetUIComboBox().SelectedIndex = 0;
                    return true;
                }
                return false;
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex);
                return false;
            }
        }

        private void LoadTimePeriodByOrg(decimal year)
        {

            int periodSelected = 0;
            UICommand command = base.GetCommandByKey(DDCMD_TIMEPERIOD);
            bool isSearch = false;

            if (command != null)
            {
                if (command.GetUIComboBox().SelectedIndex >= 0)
                    periodSelected = ((LST_SALPERIOD)command.GetUIComboBox().SelectedItem.DataRow).ENDDATE.Value.Month;
            }

            _lstOrgPeriod = Service.PayrollClient.GetActiveSalaryPeriod(year, ucOrgTreeview.OrgId);

            base.SetDataSourceToDropdownCommand(DDCMD_TIMEPERIOD, _lstOrgPeriod, "NAME", "ID", true);

            if (_lstOrgPeriod.Count > 0)
            {
                if (command != null)
                {
                    command.GetUIComboBox().SelectedIndex = 0;
                    if (periodSelected == 0)
                        periodSelected = DateTime.Now.Month;

                    for (int i = 0; i < _lstOrgPeriod.Count - 1; i++)
                    {
                        if (_lstOrgPeriod[i].ENDDATE.Value.Month >= periodSelected && _lstOrgPeriod[i].COSTATUS == (decimal?)ColexStatus.Working)
                        {
                            command.GetUIComboBox().SelectedIndex = i;
                            isSearch = true;
                            break;
                        }
                    }
                    if (!isSearch)
                    {
                        for (int i = _lstOrgPeriod.Count - 1; i >= 0; i--)
                        {
                            if (_lstOrgPeriod[i].ENDDATE.Value.Month < periodSelected && _lstOrgPeriod[i].COSTATUS == (decimal?)ColexStatus.Working)
                            {
                                command.GetUIComboBox().SelectedIndex = i;
                                break;
                            }
                        }
                    }
                }

                //LoadData(false, false);
            }
            else
            {
                base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Delete)).Enabled = Janus.Windows.UI.InheritableBoolean.False;
            }
        }

        private void InitGrid()
        {
            try
            {
                GridEXColumn col;
                UICommand command = base.GetCommandByKey(DDCMD_TIMEPERIOD);
                var objOrgPeriod = _lstOrgPeriod.Find(o => o.ID == (decimal?)command.GetUIComboBox().SelectedValue);
                List<TIME_CFN> columnDisplay;

                jgridData.RootTable.RemoveFilter();
                jgridData.FrozenColumns = 5;
                jgridData.RootTable.Columns.Clear();
                col = new GridEXColumn();
                col.ActAsSelector = true;
                col.Key = GCOL_SELECTOR;
                col.EditType = EditType.CheckBox;
                col.FilterEditType = FilterEditType.CheckBox;
                col.Width = 20;
                jgridData.RootTable.Columns.Add(col);

                col = new GridEXColumn();
                col.Key = GCOL_EMPLOYEEID;
                col.DataMember = GCOL_EMPLOYEEID;
                col.Caption = GCOL_EMPLOYEEID;
                col.EditType = EditType.NoEdit;
                col.FilterEditType = FilterEditType.TextBox;
                col.ColumnType = ColumnType.Text;
                col.HeaderAlignment = TextAlignment.Center;
                col.Visible = false;
                jgridData.RootTable.Columns.Add(col);

                col = new GridEXColumn();
                col.Key = GCOL_EMPLOYEECODE;
                col.DataMember = GCOL_EMPLOYEECODE;
                col.Caption = "MÃ NHÂN VIÊN";
                col.EditType = EditType.NoEdit;
                col.FilterEditType = FilterEditType.TextBox;
                col.ColumnType = ColumnType.Text;
                col.HeaderAlignment = TextAlignment.Center;
                col.Width = 80;
                jgridData.RootTable.Columns.Add(col);

                col = new GridEXColumn();
                col.Key = GCOL_EMPLOYEENAME;
                col.DataMember = GCOL_EMPLOYEENAME;
                col.Caption = "TÊN NHÂN VIÊN";
                col.EditType = EditType.NoEdit;
                col.FilterEditType = FilterEditType.TextBox;
                col.ColumnType = ColumnType.Text;
                col.HeaderAlignment = TextAlignment.Center;
                col.Width = 150;
                jgridData.RootTable.Columns.Add(col);

                col = new GridEXColumn();
                col.Key = GCOL_ORGNAME;
                col.DataMember = GCOL_ORGNAME;
                col.Caption = "PHÒNG BAN/BỘ PHẬN";
                col.EditType = EditType.NoEdit;
                col.FilterEditType = FilterEditType.TextBox;
                col.ColumnType = ColumnType.Text;
                col.HeaderAlignment = TextAlignment.Center;
                col.Width = 150;
                jgridData.RootTable.Columns.Add(col);

                command = base.GetCommandByKey(DDCMD_DISPLAYMODE);

                switch ((ColexDisplayMode)((decimal)command.GetUIComboBox().SelectedValue))
                {
                    case ColexDisplayMode.BySign:
                        jgridData.FrozenColumns = 4;
                        columnDisplay = TimeUtil.GetSupportDisplayColumn(this.GetType().Name);
                        columnDisplay.Sort((x, y) => Convert.ToInt32(x.Windex - y.Windex));
                        _usingSignCollection = string.Empty;

                        if (columnDisplay.Count > 0)
                        {
                            CO_SIGN_LST obj;
                            _lstSign = new List<CO_SIGN_LST>();
                            foreach (var item in columnDisplay)
                            {
                                obj = new CO_SIGN_LST();
                                obj.CODE = item.Id;
                                obj.NAME = item.Text;
                                _lstSign.Add(obj);

                                col = new GridEXColumn();
                                col.Key = item.Id;
                                col.DataMember = item.Id;
                                col.Caption = item.Id;
                                col.HeaderAlignment = TextAlignment.Center;
                                col.EditType = EditType.NoEdit;
                                col.FilterEditType = FilterEditType.TextBox;
                                col.ColumnType = ColumnType.Text;
                                col.Width = 40;
                                col.HeaderToolTip = item.Text;
                                jgridData.RootTable.Columns.Add(col);

                                if (item.WDataType.HasValue)
                                {
                                    switch ((WorkSignDataType)item.WDataType)
                                    {
                                        case WorkSignDataType.Number:
                                            col.TextAlignment = TextAlignment.Far;
                                            break;
                                        case WorkSignDataType.String:
                                            col.TextAlignment = TextAlignment.Near;
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                //if (!String.IsNullOrEmpty(item.FormatString))
                                //{
                                //    col.FormatString = item.FormatString;
                                //}

                                _usingSignCollection += "," + item.Id;
                            }
                        }
                        else
                        {
                            _lstSign = HiStaff.iSystem.Data.ALLCOSIGN.FindAll(obj => obj.STATUS == 1
                                                                           && obj.EFFECTDATE <= objOrgPeriod.STARTDATE
                                                                           && (obj.ENDDATE == null || obj.ENDDATE >= objOrgPeriod.ENDDATE)
                                                                           && (MngSignGroup == 0 || obj.GROUPID == (int)MngSignGroup)
                                                                           && obj.DISPLAY == (int)WorkSignDisplay.Show);
                            //_lstSign = OracleHelper.ExcuteSelectMultiObject<CO_SIGN_LST>("PKG_HCM_COLEX", "PRS_SIGN_SUMMARY", objSSign);
                            foreach (var item in _lstSign)
                            {
                                col = new GridEXColumn();
                                col.Key = item.CODE;
                                col.DataMember = item.CODE;
                                col.Caption = item.CODE;
                                col.HeaderAlignment = TextAlignment.Center;
                                col.EditType = EditType.NoEdit;
                                col.FilterEditType = FilterEditType.TextBox;
                                col.ColumnType = ColumnType.Text;
                                col.Width = 40;
                                col.HeaderToolTip = item.NAME;
                                jgridData.RootTable.Columns.Add(col);

                                if (item.DATATYPEID.HasValue)
                                {
                                    switch ((WorkSignDataType)item.DATATYPEID)
                                    {
                                        case WorkSignDataType.Number:
                                            col.TextAlignment = TextAlignment.Far;
                                            break;
                                        case WorkSignDataType.String:
                                            col.TextAlignment = TextAlignment.Near;
                                            break;
                                        default:
                                            break;
                                    }
                                }

                                _usingSignCollection += "," + item.CODE;
                            }
                        }

                        //GCOL_NODATA
                        col = new GridEXColumn();
                        col.Key = GCOL_NODATA;
                        col.DataMember = GCOL_NODATA;
                        col.Visible = false;
                        col.EditType = EditType.NoEdit;
                        jgridData.RootTable.Columns.Add(col);
                        break;
                    case ColexDisplayMode.BySignWithDate:
                        col = new GridEXColumn();
                        col.Key = GCOL_WORKINGDAY;
                        col.DataMember = GCOL_WORKINGDAY;
                        col.Caption = "NGÀY";
                        col.EditType = EditType.NoEdit;
                        col.FilterEditType = FilterEditType.TextBox;
                        col.HeaderAlignment = TextAlignment.Center;
                        col.TextAlignment = TextAlignment.Center;
                        col.FormatString = Constant.FORMAT_DATE;
                        col.Width = 100;
                        //col.Selectable = false;
                        jgridData.RootTable.Columns.Add(col);

                        columnDisplay = TimeUtil.GetSupportDisplayColumn(this.GetType().Name);
                        columnDisplay.Sort((x, y) => Convert.ToInt32(x.Windex - y.Windex));
                        _usingSignCollection = string.Empty;

                        if (columnDisplay.Count > 0)
                        {
                            foreach (var item in columnDisplay)
                            {
                                col = new GridEXColumn();
                                col.Key = item.Id;
                                col.DataMember = item.Id;
                                col.Caption = item.Id;
                                col.HeaderAlignment = TextAlignment.Center;
                                col.EditType = EditType.NoEdit;
                                col.FilterEditType = FilterEditType.TextBox;
                                col.ColumnType = ColumnType.Text;
                                col.Width = 40;
                                col.HeaderToolTip = item.Text;
                                if (item.WDataType.HasValue)
                                {
                                    switch ((WorkSignDataType)item.WDataType)
                                    {
                                        case WorkSignDataType.Number:
                                            col.TextAlignment = TextAlignment.Far;
                                            break;
                                        case WorkSignDataType.String:
                                            col.TextAlignment = TextAlignment.Near;
                                            break;
                                        case WorkSignDataType.DateTime:
                                            col.FormatString = Constant.FORMAT_TIME;
                                            col.TextAlignment = TextAlignment.Center;
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                if (!String.IsNullOrEmpty(item.FormatString))
                                {
                                    col.FormatString = item.FormatString;
                                }

                                jgridData.RootTable.Columns.Add(col);
                                _usingSignCollection += "," + item.Id;
                            }
                        }
                        else
                        {
                            _lstSign = HiStaff.iSystem.Data.ALLCOSIGN.FindAll(obj => obj.STATUS == 1
                                                                         && (obj.EFFECTDATE <= objOrgPeriod.STARTDATE)
                                                                         && (obj.ENDDATE == null || obj.ENDDATE >= objOrgPeriod.ENDDATE)
                                                                         && (MngSignGroup == 0 || obj.GROUPID == (int)MngSignGroup)
                                                                         && obj.DISPLAY == (int)WorkSignDisplay.Show);
                            //_lstSign = OracleHelper.ExcuteSelectMultiObject<CO_SIGN_LST>("PKG_HCM_COLEX", "PRS_SIGN_SUMMARY", objSSign);
                            foreach (var item in _lstSign)
                            {
                                col = new GridEXColumn();
                                col.Key = item.CODE;
                                col.DataMember = item.CODE;
                                col.Caption = item.CODE;
                                col.EditType = EditType.NoEdit;
                                col.HeaderAlignment = TextAlignment.Center;
                                col.FilterEditType = FilterEditType.TextBox;
                                col.ColumnType = ColumnType.Text;
                                col.Width = 40;
                                col.HeaderToolTip = item.NAME;

                                if (item.DATATYPEID.HasValue)
                                {
                                    switch ((WorkSignDataType)item.DATATYPEID)
                                    {
                                        case WorkSignDataType.Number:
                                            col.TextAlignment = TextAlignment.Far;
                                            break;
                                        case WorkSignDataType.String:
                                            col.TextAlignment = TextAlignment.Near;
                                            break;
                                        case WorkSignDataType.DateTime:
                                            col.FormatString = Constant.FORMAT_TIME;
                                            col.TextAlignment = TextAlignment.Center;
                                            break;
                                        default:
                                            break;
                                    }
                                }

                                jgridData.RootTable.Columns.Add(col);
                                _usingSignCollection += "," + item.CODE;
                            }
                        }

                        col = new GridEXColumn();
                        col.Key = GCOL_SUNDAY;
                        col.DataMember = GCOL_SUNDAY;
                        col.Visible = false;
                        col.EditType = EditType.NoEdit;
                        jgridData.RootTable.Columns.Add(col);
                        break;

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }

        private void LoadData(bool isLoadByEmp, bool reInitGrid)
        {
            DataTable dsSource;
            UICommand command;
            CO_SUM_SEARCH objSearch = new CO_SUM_SEARCH();
            objSearch.ORGID = ConvertHelper.ToDecimal(ucOrgTreeview.SelectedNode.Name);
            objSearch.PERIODID = (decimal?)base.GetCommandByKey(DDCMD_TIMEPERIOD).GetUIComboBox().SelectedValue;
            objSearch.GROUPID = (int)MngSignGroup;
            objSearch.STATUS = 1;

            if (isLoadByEmp)
            {
                objSearch.CODE = txtSearchEmp.Text.Trim();
            }
            else
            {
                objSearch.CODE = string.Empty;
            }
            if (objSearch.PERIODID != null)
            {
                if (reInitGrid) InitGrid();
                objSearch.USINGSIGNLST = _usingSignCollection + ",";
                command = base.GetCommandByKey(DDCMD_DISPLAYMODE);

                switch ((ColexDisplayMode)((decimal)command.GetUIComboBox().SelectedValue))
                {
                    case ColexDisplayMode.BySign:
                        dsSource = Service.ExcuteStoreToDataTable("PRS_SUMBYSIGN", objSearch);
                        if (dsSource != null) jgridData.SetDataBinding(dsSource, "");
                        break;

                    case ColexDisplayMode.BySignWithDate:
                        dsSource = Service.ExcuteStoreToDataTable("PRS_SUMSIGNWITHDATE", objSearch);
                        if (dsSource != null)
                        {
                            jgridData.SetDataBinding(dsSource, "");
                        }
                        break;
                }
                LST_SALPERIOD SelectedPeriod;
                SelectedPeriod = _lstOrgPeriod.Find(o => o.ID == objSearch.PERIODID);
                ColexStatus status = ColexStatus.FinalClose;
                if (SelectedPeriod != null)
                    status = (ColexStatus)SelectedPeriod.COSTATUS;

                switch (status)
                {
                    case ColexStatus.Working:
                        base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Calculate)).Enabled = Janus.Windows.UI.InheritableBoolean.True;
                        SetEnabledCommandDelete = true;
                        break;
                    case ColexStatus.Close:
                    case ColexStatus.FinalClose:
                        base.GetCommandByKey(ConvertHelper.ConvertEnumToString<CommandBarManager.ActionCommand>(CommandBarManager.ActionCommand.Calculate)).Enabled = Janus.Windows.UI.InheritableBoolean.False;
                        SetEnabledCommandDelete = false;
                        break;
                    default:
                        break;
                }
            }
            else
            {
                SetToolStripButtonBar(CommandBarManager.ActionCommand.Null);
            }
        }

        private bool DeleteDataRgtBySign(decimal? employeeid, string signcode, decimal periodid)
        {
            CO_DAYRGT objDel = new CO_DAYRGT();
            objDel.EMPLOYEEID = employeeid;
            objDel.CODE = signcode;
            objDel.PERIODID = periodid;

            Service.ExcuteStoreNonQuery("APRD_CO_DAYRGT", objDel);

            return true;
        }

        private bool DeleteDataRgtBySignWithDate(decimal? employeeid, string signcode, DateTime workingdate)
        {
            CO_DAYRGT objDel = new CO_DAYRGT();
            objDel.EMPLOYEEID = employeeid;
            objDel.CODE = signcode;
            objDel.WORKINGDAY = workingdate;

            Service.ExcuteStoreNonQuery("APRD_CO_DAYRGT", objDel);

            return true;
        }

        private void jgridData_FormattingRow(object sender, RowLoadEventArgs e)
        {
            UICommand command;
            command = base.GetCommandByKey(DDCMD_DISPLAYMODE);
            Janus.Windows.GridEX.GridEXFormatStyle formatStyle = new Janus.Windows.GridEX.GridEXFormatStyle();
            formatStyle.BackColor = Color.LightPink;

            Janus.Windows.GridEX.GridEXFormatStyle formatStyleNoData = new Janus.Windows.GridEX.GridEXFormatStyle();
            formatStyleNoData.ForeColor = Color.Red;
            try
            {
                switch ((ColexDisplayMode)command.GetUIComboBox().SelectedValue)
                {
                    case ColexDisplayMode.BySign:
                        if (jgridData.RootTable.Columns.Contains(GCOL_NODATA))
                        {
                            if (e.Row.Cells[GCOL_NODATA].Value != null && e.Row.Cells[GCOL_NODATA].Value.ToString().Equals("1"))
                            {
                                e.Row.RowStyle = formatStyleNoData;
                            }
                        }
                        break;

                    case ColexDisplayMode.BySignWithDate:
                        if (jgridData.RootTable.Columns.Contains(GCOL_SUNDAY))
                        {
                            if (e.Row.Cells[GCOL_SUNDAY].Value != null && e.Row.Cells[GCOL_SUNDAY].Value.ToString().Equals("1"))
                            {
                                e.Row.RowStyle = formatStyle;
                            }
                        }
                        break;
                }
            }
            catch (Exception)
            {
                throw;
            }

        }

        #endregion

        #region Override & Vitual Functions

        protected override bool CommandValueChanged(Janus.Windows.UI.CommandBars.UICommand Command)
        {
            TextBox txtYear;
            decimal year;
            bool isConvert;
            switch (Command.Key)
            {
                case TCMD_YEAR:
                    txtYear = base.GetCommandByKey(TCMD_YEAR).GetTextBox();
                    isConvert = decimal.TryParse(txtYear.Text, out year);

                    if (txtYear.Text.Trim().Length >= 4 & isConvert)
                    {
                        LoadTimePeriodByOrg(year);

                        if (txtYear.Text.Trim().Length >= 4 & isConvert)
                        {
                            if (txtSearchEmp.Text.Trim() == string.Empty)
                                LoadData(false, true);
                            else LoadData(true, true);
                        }
                    }
                    break;

                case DDCMD_TIMEPERIOD:
                    txtYear = base.GetCommandByKey(TCMD_YEAR).GetTextBox();
                    isConvert = decimal.TryParse(txtYear.Text, out year);

                    if (txtYear.Text.Trim().Length >= 4 & isConvert)
                    {
                        if (txtSearchEmp.Text.Trim() == string.Empty)
                            LoadData(false, true);
                        else LoadData(true, true);
                    }
                    break;

                case DDCMD_DISPLAYMODE:
                    txtYear = base.GetCommandByKey(TCMD_YEAR).GetTextBox();
                    isConvert = decimal.TryParse(txtYear.Text, out year);

                    if (txtYear.Text.Trim().Length >= 4 & isConvert)
                    {
                        if (txtSearchEmp.Text.Trim() == string.Empty)
                            LoadData(false, true);
                        else LoadData(true, true);
                    }
                    break;
                default:
                    break;
            }
            return true;
        }

        protected override bool AddNewButtonClick()
        {
            List<EMPLOYEE_SELECTION> lstSelection = new List<EMPLOYEE_SELECTION>();
            EMPLOYEE_SELECTION objSelection;
            foreach (var item in jgridData.GetCheckedRows())
            {
                objSelection = Service.ProfileClient.GetEmployeeSelection(new EMPLOYEE_SEARCH
                {
                    ID = ConvertHelper.ToDecimal(item.Cells[GCOL_EMPLOYEEID].Value)
                })[0];
                if (lstSelection.Find(s => s.ID == objSelection.ID) != null)
                {
                    continue;
                }
                lstSelection.Add(objSelection);
            }

            _frmRgt = GetRgtFormInstance();
            _frmRgt.ListEmployeeRegist = lstSelection;
            _frmRgt.ShowDialog();

            if (_frmRgt.RegisterResult == DialogResult.OK)
            {
                if (txtSearchEmp.Text.Trim() == string.Empty)
                    LoadData(false, true);
                else LoadData(true, true);
            }

            return false;
        }

        protected virtual BaseRegister GetRgtFormInstance()
        {
            return new BaseRegister();
        }

        protected override bool DeleteButtonClick()
        {
            CO_SIGN_LST objSearch;
            DialogResult dlgResult = DialogResult.No;
            UICommand command = base.GetCommandByKey(DDCMD_DISPLAYMODE);
            decimal? periodid;
            string signcode;

            switch ((ColexDisplayMode)command.GetUIComboBox().SelectedValue)
            {
                case ColexDisplayMode.BySign:
                    command = base.GetCommandByKey(DDCMD_TIMEPERIOD);
                    periodid = (decimal?)command.GetUIComboBox().SelectedValue;
                    if (jgridData.GetCheckedRows().Length > 0 && periodid.HasValue)
                    {
                        if (jgridData.CurrentColumn == null)
                        {
                            MessageBox.Show(GetMessageById(Constant.MSG_SIGNINVALID),
                                            this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return false;
                        }
                        signcode = jgridData.CurrentColumn.DataMember;

                        objSearch = HiStaff.iSystem.Data.ALLCOSIGN.Find(s => s.CODE == signcode);
                        if (objSearch == null)
                        {
                            MessageBox.Show(GetMessageById(Constant.MSG_SIGNINVALID),
                                            this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return false;
                        }

                        dlgResult = MessageBox.Show(string.Format(GetMessageById(Constant.MSG_DELRGTBYSIGN_CFM), signcode, command.GetUIComboBox().Text),
                                                    this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dlgResult == DialogResult.Yes)
                        {
                            foreach (var item in jgridData.GetCheckedRows())
                            {
                                DeleteDataRgtBySign(ConvertHelper.ToDecimal(item.Cells[GCOL_EMPLOYEEID].Value),
                                                   signcode, periodid.Value);
                            }
                        }
                    }
                    break;
                case ColexDisplayMode.BySignWithDate:
                    if (jgridData.GetCheckedRows().Length > 0)
                    {
                        if (jgridData.CurrentColumn == null)
                        {
                            MessageBox.Show(GetMessageById(Constant.MSG_SIGNINVALID),
                                               this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return false;
                        }
                        signcode = jgridData.CurrentColumn.DataMember;

                        objSearch = HiStaff.iSystem.Data.ALLCOSIGN.Find(s => s.CODE == signcode);
                        if (objSearch == null)
                        {
                            MessageBox.Show(GetMessageById(Constant.MSG_SIGNINVALID),
                                            this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return false;
                        }

                        dlgResult = MessageBox.Show(string.Format(GetMessageById(Constant.MSG_DELRGTBYSIGNWITHDATE_CFM), signcode),
                                                    this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                        if (dlgResult == DialogResult.Yes)
                        {
                            foreach (var item in jgridData.GetCheckedRows())
                            {
                                DeleteDataRgtBySignWithDate(ConvertHelper.ToDecimal(item.Cells[GCOL_EMPLOYEEID].Value), signcode,
                                                            Convert.ToDateTime(item.Cells[GCOL_WORKINGDAY].Value));
                            }
                        }
                    }
                    break;
            }

            if (dlgResult == DialogResult.Yes)
            {
                if (txtSearchEmp.Text.Trim() == string.Empty)
                    LoadData(false, false);
                else LoadData(true, false);
            }

            return false;
        }

        protected override bool CalculateButtonClick()
        {
            this.Cursor = Cursors.WaitCursor;
            DialogResult dlgResult;
            _objCal = new CO_SUM_SEARCH();
            _objCal.GROUPID = (decimal?)MngSignGroup;
            _objCal.ORGID = ucOrgTreeview.OrgId;
            _objCal.EMPLIST = string.Empty;
            _objCal.PERIODID = (decimal?)base.GetCommandByKey(DDCMD_TIMEPERIOD).GetUIComboBox().SelectedValue;

            if (jgridData.GetCheckedRows().Length > 0)
            {
                foreach (var item in jgridData.GetCheckedRows())
                {
                    if (!_objCal.EMPLIST.Contains(item.Cells[GCOL_EMPLOYEEID].Value + ","))
                    {
                        _objCal.EMPLIST += item.Cells[GCOL_EMPLOYEEID].Value + ",";
                    }
                }
            }

            if (_objCal.EMPLIST != null && _objCal.EMPLIST.Length > 3000)
            {
                dlgResult = MessageBox.Show(GetMessageById(Constant.MSG_MAX_EMPCHOSEN),
                                            this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (dlgResult == DialogResult.No)
                {
                    return false;
                }
                else
                {
                    _objCal.EMPLIST = null;
                    _objCal.ORGID = ConvertHelper.ToDecimal(ucOrgTreeview.SelectedNode.Name);
                }
            }

            dlgResult = MessageBox.Show(GetMessageById(Constant.MSG_SUMCOLEX_CFM), this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dlgResult == DialogResult.Yes)
            {
                ExcuteAsynchronous();
                return true;
            }
            this.Cursor = Cursors.Default;
            return false;
        }

        protected override bool AsynchronousFunctionWithBGW(System.ComponentModel.BackgroundWorker bgWorker)
        {
            try
            {
                bgWorker.ReportProgress(0, string.Format(GetMessageById("MSG_CALCOLEX"), ""));
                var lstFml = Service.TimeClient.GetFormularForCal(_objCal);
                var count = lstFml.Count + 2;
                var step = 1;
                var percent = (step * 100 / count);

                bgWorker.ReportProgress(percent, string.Format(GetMessageById("MSG_CALCOLEX"), ""));
                step++;
                Service.ExcuteStoreNonQuery("PKG_CALCOLEX", "PRI_CRECOLEX", _objCal);
                bgWorker.ReportProgress(percent, string.Format(GetMessageById("MSG_CALCOLEX"), ""));

                var startTime = DateTime.Now;
                DateTime stepTime;
                foreach (var item in lstFml)
                {
                    step++;
                    _objCal.CODE = item.CODE;
                    _objCal.FORMULAR = item.FORMULAR;
                    _objCal.DATATYPEID = item.DATATYPEID;
                    _objCal.VIEWNAME = item.VIEWNAME;
                    Service.ExcuteStoreNonQuery("PKG_CALCOLEX", "PRU_CALCOLEX", _objCal);

                    stepTime = DateTime.Now;

                    TimeSpan aboutTime = stepTime - startTime;

                    var li = aboutTime.TotalMinutes;

                    var liOne = li / step - 2;

                    var totalMin = liOne * (count - step);
                    percent = (step * 100 / count);
                    bgWorker.ReportProgress(percent, string.Format(GetMessageById("MSG_CALCOLEX"), totalMin.ToString() + " min"));
                }

                bgWorker.ReportProgress(100, GetMessageById(Constant.MSG_SUMCOLEX_CPL));
            }
            catch (Exception ex)
            {
                bgWorker.ReportProgress(0, ex.Message);
                return false;
            }

            return true;
        }

        protected override void RunAfterWorkerCompleted(bool result)
        {
            try
            {
                if (txtSearchEmp.Text.Trim() != string.Empty)
                {
                    LoadData(true, false);
                }
                else
                {
                    LoadData(false, false);
                }
                SetStatusText(GetMessageById(Constant.MSG_LOADDATA_CPL), MessageIcon.Info);
            }
            catch (Exception ex)
            {
                WriteErrorLog(ex);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }
        }

        protected override bool LockButtonClick()
        {
            DialogResult result = MessageBox.Show(GetMessageById(Constant.MSG_LOCK_CFM), this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                PA_ORG_SALPERIOD objUdp = new PA_ORG_SALPERIOD();
                objUdp.SALPERIOD = (decimal?)base.GetCommandByKey(DDCMD_TIMEPERIOD).GetUIComboBox().SelectedValue;
                objUdp.ORGID = ucOrgTreeview.OrgId;
                objUdp.COSTATUS = (decimal)ColexStatus.Close;

                Service.ExcuteStoreNonQuery("PKG_CALCOLEX", "PRU_COLEXSTATUS", objUdp);

                MessageBox.Show(GetMessageById(Constant.MSG_LOCK_CPL), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            return false;
        }
        protected override bool UnLockButtonClick()
        {
            DialogResult result = MessageBox.Show(GetMessageById(Constant.MSG_LOCK_CFM), this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                PA_ORG_SALPERIOD objUdp = new PA_ORG_SALPERIOD();
                objUdp.SALPERIOD = (decimal?)base.GetCommandByKey(DDCMD_TIMEPERIOD).GetUIComboBox().SelectedValue;
                objUdp.ORGID = ucOrgTreeview.OrgId;
                objUdp.COSTATUS = (decimal)ColexStatus.Working;

                Service.ExcuteStoreNonQuery("PKG_CALCOLEX", "PRU_COLEXSTATUS", objUdp);

                MessageBox.Show(GetMessageById(Constant.MSG_UNLOCK_CPL), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Information);
                return true;
            }
            return false;
        }

        protected override void SetToolStripButtonBar(CommandBarManager.ActionCommand cmd)
        {
            switch (cmd)
            {
                case CommandBarManager.ActionCommand.Lock:
                    SetEnableCommand(CommandBarManager.ActionCommand.Calculate, false);
                    SetEnableCommand(CommandBarManager.ActionCommand.Lock, false);
                    SetEnableCommand(CommandBarManager.ActionCommand.UnLock, true);
                    break;
                case CommandBarManager.ActionCommand.UnLock:
                    SetEnableCommand(CommandBarManager.ActionCommand.Calculate, true);
                    SetEnableCommand(CommandBarManager.ActionCommand.Lock, true);
                    SetEnableCommand(CommandBarManager.ActionCommand.UnLock, false);
                    break;
                default:
                    break;
            }
        }

        #endregion
    }
}
